package com.lyl.common.config;

import cn.hutool.json.JSONUtil;
import com.lyl.common.annotation.IgnoreResponseWrapper;
import com.lyl.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Arrays;

/**
 * @author Mr.Luo
 * @desc 全局响应处理器
 */
@Slf4j
@RestControllerAdvice
public class DefaultGlobalResponseHandler implements ResponseBodyAdvice<Object> {
    /**
     * 排除的swagger的请求
     */
    private static final String[] EXCLUDE = {
            //swagger程序
            "Swagger2Controller",
            "Swagger2ControllerWebMvc",
            "ApiResourceController",

            // actuator
            "OperationHandler",
            "WebMvcLinksHandler"
    };

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return needWrapper(methodParameter);
    }

    /**
     * 判断是否需要包装
     *
     * @param methodParameter 方法参数
     * @return true/false
     */
    private boolean needWrapper(MethodParameter methodParameter) {
        return !(methodParameter.getParameterType().isAssignableFrom(Result.class)
                || methodParameter.hasMethodAnnotation(IgnoreResponseWrapper.class)
                || methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseWrapper.class)
                || Arrays.asList(EXCLUDE).contains(methodParameter.getDeclaringClass().getSimpleName())
        );
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String) {
            return JSONUtil.toJsonStr(Result.ok(body));
        } else if (body instanceof Result) {
            return body;
        }
        return Result.ok(body);
    }
}
